package threadpool

import (
	"container/list"
	"errors"
	"sync"
)

type Tasktype interface {
	Task()
}

type Queue struct {
	list  *list.List
	mutex sync.RWMutex
}

func GetQueue() *Queue {
	return &Queue{
		list: list.New(),
	}
}

func (queue *Queue) IsEmpty() bool {
	return queue.Len() == 0
}

func (queue *Queue) Push(data Tasktype) {
	if data == nil {
		return
	}
	queue.mutex.Lock()
	queue.list.PushBack(data)
	queue.mutex.Unlock()
}

func (queue *Queue) Pop() (Tasktype, error) {
	queue.mutex.Lock()

	if element := queue.list.Front(); element != nil {
		queue.list.Remove(element)
		var task Tasktype = (element.Value).(Tasktype)
		return task, nil
	}
	defer queue.mutex.Unlock()
	return nil, errors.New("元素为空")
}

func (queue *Queue) Clear() {
	queue.mutex.Lock()
	for element := queue.list.Front(); element != nil; {
		elementNext := element.Next()
		queue.list.Remove(element)
		element = elementNext
	}
	queue.mutex.Unlock()
}

func (queue *Queue) Len() int {
	queue.mutex.RLock()
	c := queue.list.Len()
	queue.mutex.RUnlock()
	return c
}
